var fs = require('fs');
var path = require('path');

module.exports = {
    init: async function() {
        return new Promise(async (resolve, reject) => {
            var files = ['update_size', 'update_aHash', 'update_bHash', 'update_d_i'];
            console.log('to update:', files);
            for (var i = 0; i < files.length; i++) {
                var file = files[i];
                if (file.match(/^update/)) {
                    try {
                        var obj = require(path.join(__dirname, file));
                        var field = file.replace('update_', '');
                        console.log('\nstart update:', field);
                        var failed = await obj.init();
                        if (failed && failed.length) {
                            console.log('\tupdate', field, 'failed:', failed.map( (x, i) => {
                                var s = "";
                                for (var key in x) {
                                    s += '\n\t' + key + ': ' + x[key].toString().trim().replace(/\n/g, '\n\t' + " ".repeat(key.length + 2));
                                }
                                return s;
                            } ).join(''));
                        }
                        console.log('update completed:', field, '\n\n');
                    } catch (e) {
                        console.log('require failed:', file, '\n\terr:', e);
                    }

                }
            }
            resolve();
        })
    }
}
